# koroFileHeader at Yungoal acer
# Create: 2023-10-20 17:43:57
# LastEdit: 2023-10-26 10:25:18
"""标签
https://next.api.aliyun.com/api-tools/sdk/Tag

在多对多(many-to-many)关系中添加添加额外的属性字段
https://docs.djangoproject.com/zh-hans/4.2/topics/db/models/#extra-fields-on-many-to-many-relationships
"""
__author__ = '749B'


from django.contrib import admin
from django.db import models


class TagKey(models.Model):
    key = models.CharField(max_length=128)
    account = models.ForeignKey('Account', on_delete=models.CASCADE)

    def __str__(self):
        return self.key

    class Meta:
        verbose_name = '标签'
        verbose_name_plural = '标签'
        # 联合唯一约束
        constraints = [
            models.UniqueConstraint(
                fields=['account', 'key'],
                name='unique_account_tagkey',
                ),
            ]

class TagKeyAdmin(admin.ModelAdmin):
    list_display = ['key', 'account']
    list_filter = ['account']

    actions = ['list_tag_value_rg']

    @admin.action(description='资源组标签值展示')
    def list_tag_value_rg(self, request, queryset):
        for key_obj in queryset:
            for value_obj in (
                key_obj.tagvaluerg_set.values('value')
                .annotate(count=models.Count('value'))
                .order_by('-count')[:5]):
                self.message_user(
                    request,
                    f"{key_obj.key}={value_obj['value']}({value_obj['count']})",
                    'info',
                    )


class TagValueRg(models.Model):
    tag_key = models.ForeignKey('TagKey', on_delete=models.CASCADE)
    resource_group = models.ForeignKey('ResourceGroup', on_delete=models.CASCADE)
    value = models.CharField(max_length=128)

    def __str__(self):
        return f'{self.tag_key}={self.value}'

class TagValueRes(models.Model):
    tag_key = models.ForeignKey('TagKey', on_delete=models.CASCADE)
    resource = models.ForeignKey('Resource', on_delete=models.CASCADE)
    value = models.CharField(max_length=128)

    def __str__(self):
        return f'{self.tag_key}={self.value}'
